package com.lv.common.adapter

import android.provider.SyncStateContract.Helpers.update
import androidx.annotation.NonNull
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.lv.common.bean.CommonSelectedBean


/**
 * 作者： ygx
 * 创建日期：2023/3/13 10:08 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：
 */
class ViewPagerCommon2Adapter(
    @NonNull fragmentManager: FragmentManager,
    lifecycle: Lifecycle,
    fragmentList: List<CommonSelectedBean>,
    listener: TabPagerListener
) :
    FragmentStateAdapter(fragmentManager, lifecycle) {
    private val fragmentList: List<CommonSelectedBean>
    private val fragmentIds: MutableList<Long> = ArrayList() //用于存储更新fragment的特定标识
    private val creatIds: HashSet<Long> = HashSet() //得用hashset防重，用于存储adapter内的顺序
    var mListener: TabPagerListener? = null

    init {
        this.fragmentList = fragmentList
        this.mListener = listener
        update(fragmentList)
    }

    fun update(fragmentLists: List<CommonSelectedBean>) {
        fragmentIds.clear()
        for (i in fragmentLists.indices) {
//            fragmentIds.add((fragmentLists[i] as ViewPagerFragment).getTypeId())
            fragmentIds.add(i.hashCode().toLong())
        }
    }

    @NonNull
    override fun createFragment(position: Int): Fragment {
        val ids = fragmentIds[position]
        creatIds.add(ids) //创建的时候将未添加的fragment添加进来，每次刷新都会调用这里，其次调用containsItem
//        return fragmentList[position]
        return mListener?.getFragment(position)!!
    }

    override fun getItemCount(): Int {
        return fragmentList.size
    }

    /**
     * 这两个方法必须重写，作为数据改变刷新检测的工具
     * @param position
     * @return
     */
    override fun getItemId(position: Int): Long {
        return fragmentIds[position]
    }

    override fun containsItem(itemId: Long): Boolean {
        return creatIds.contains(itemId)
    }

    interface TabPagerListener {
        fun getFragment(position: Int): Fragment?
    }
}